var nodeJsx = require('node-jsx');
nodeJsx.install({extension: '.jsx'});
var express = require('express');
var React = require('react');
var ReactDom = require('react-dom/server');
var renderToString = ReactDom.renderToString;
var ReactRouter = require('react-router');
var RouterContext = ReactRouter.RouterContext;
var rc = React.createFactory(RouterContext);
var match = ReactRouter.match;
var routes = require('../public/javascripts/index/route.jsx');
module.exports = function (app) {
    app.use((req, res) => {
        //res.render('index', {
        //    title: 'Express',
        //    html: '<div id="main"></div>',
        //    script: '<script src="javascripts/index.js"></script>'
        //});
        //match({Route, location: req.url}, (err, redirectLocation, renderProps) => {
        //    if (err) {
        //        res.status(500).end(`Internal Server Error ${err}`);
        //    } else if (redirectLocation) {
        //        res.redirect(redirectLocation.pathname + redirectLocation.search);
        //    } else if (renderProps) {
        //        var html = ReactDom.renderToString(route);
        //        res.render('index', {
        //            title: 'Express',
        //            html: html,
        //            script: '<script src="javascripts/index.js"></script>'
        //        });
        //    } else {
        //        res.status(404).end('Not found');
        //    }
        //});
        match({routes, location: req.url}, (error, redirectLocation, renderProps) => {
            if (error) {
                res.status(500).send(error.message)
            } else if (redirectLocation) {
                res.redirect(302, redirectLocation.pathname + redirectLocation.search)
            } else if (renderProps) {
                // You can also check renderProps.components or renderProps.routes for
                // your "not found" component or route respectively, and send a 404 as
                // below, if you're using a catch-all route.
                var html = '<div id="main">' + renderToString(rc(renderProps)) + '</div>';
                res.render('index', {
                    title: 'Express',
                    html: html,
                    script: '<script src="javascripts/index.js"></script>'
                });
            } else {
                res.status(404).send('Not found')
            }
        })
    });
};
